package com.thread.dome01;
/*
龟兔赛跑
 */
public class Race implements Runnable {
    //胜利者是否出现，定义静态常量
    private static String winner;
    //1.确定赛道：重新Runnable接口，本质就是线程的接口继承
    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            //3.模拟兔子睡觉,跑20步，兔子睡觉5毫秒
            if (Thread.currentThread().getName().equals("兔子") && i%20==0){
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //判断是否结束比赛，比赛结束，停止程序
            boolean flag =gameOver(i);
            if (flag){
               break;
            }
            System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
        }
    }
    //2.判断赛道是否到达重点（赛道结束）
    private boolean gameOver( int step){
        if(winner!= null){ //胜利者出现了
            return true;
        }
        if (step==100){
            winner = Thread.currentThread().getName();
            System.out.println("胜利者是："+winner);
            return true;
        }
        return false;
    }

//3.主程序调用，看哪个线程先执行完毕（先执行100次线程）
    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race,"乌龟").start();
        new Thread(race,"兔子").start();
    }
}
